<template>
    <div class="listVue">
        <el-select v-model="currentWeChat.currentUserWechatName" placeholder="选择微信AI客服" style="width: 100%;" @change="weChatChange">
            <el-option v-for="item in weChatList" :key="item.id" :label="item.wechatName" :value="item"></el-option>
        </el-select>
        <div class="automaticResponseBtn" @click="toManage">
            管理自动回复
            <span v-if="current===2">{{ automaticResponseNumber.friend}}/{{automaticResponseNumber.allFriend }}</span>
            <span v-if="current===3">{{ automaticResponseNumber.group}}/{{automaticResponseNumber.allGroup }}</span>
        </div>
        <div class="flex_between margin10">
            <el-select v-model="automaticResponse" placeholder="是否开启AI回复" style="width: 48%;" @change="automaticResponseChange">
                <el-option v-for="item in automaticResponses" :key="item.name" :label="item.name" :value="item"></el-option>
            </el-select>
            <el-select v-model="category" placeholder="选择分组" style="width: 48%;" @change="categoryChange" clearable>
                <el-option v-for="item in categoryList" :key="item.id" :label="item.name" :value="item"></el-option>
            </el-select>
        </div>
        <div class="flex_between margin10">
            <el-select v-model="tag" placeholder="选择标签" style="width: 48%;" @change="tagChange" clearable>
                <el-option v-for="item in tags" :key="item" :label="item" :value="item"></el-option>
            </el-select>
            <el-input v-model="key" style="width: 48%;" placeholder="搜索关键字" prefix-icon="el-icon-search" :clearable="true" @input="searchFun"></el-input>
        </div>
        <div class="tabVue flex_between align_center">
            <div class="tab" :class="{ active: current===1, chatTab: hasUnreadMsg }" @click="changeCurrent(1)">会话</div>
            <div class="tab" :class="{ active: current===2 }" @click="changeCurrent(2)">私聊</div>
            <div class="tab" :class="{ active: current===3 }" @click="changeCurrent(3)">群聊</div>
        </div>
        <div class="content" @scroll="handleScroll">
            <template v-if="current===1">
                <div class="item flex align_center" v-for="(item, index) in $store.state.chatting" :key="index" @click="toChat(item, 1)" :class="{active: currentChat.id===item.id}">
                    <div class="relative">
                        <img src="../../../assets/weChat.png" style="width: 44px; height: 44px;" v-if="item.type===0">
                        <img src="../../../assets/weChat_group.png" style="width: 44px; height: 44px;" v-if="item.type===1">
                        <div class="absolute" style="width: 10px; height: 10px; background: #d81e06; border-radius: 50%; right: -4px; top: -4px" v-if="item.unreadNum"></div>
                    </div>
                    <div style="width: 100%; height: 40px; display: flex; flex-direction: column; justify-content: space-between">
                        <div class="flex_between align_center" style="padding-left: 5px;">
                            <div class="name line-1 flex_1">{{item.type===0?item.friendWechatName:item.groupName}}</div>
                            <div class="time" style="padding-left: 20px;">{{formatTimeFun(item.lastSendTime)}}</div>
                        </div>
                        <div class="flex_between align_center" style="width: 100%;">
                            <div class="message line-1 flex_1" style="padding-left: 5px;">{{item.lastMessage}}</div>
                            <div class="state" :class="{active: item.automaticResponse}" @click.stop="handleStatus(item)">
                                <div class="dot dot_right" v-if="item.automaticResponse===1"></div>
                                <div class="dot dot_left" v-else></div>
                            </div>
                        </div>
                    </div>
                </div>
            </template>
            <template v-else>
                <div class="item flex align_center" v-for="(item, index) in list" :key="index" @click="toChat(item, 1)" :class="{active: currentChat.id===item.id}">
                    <img src="../../../assets/weChat.png" style="width: 44px; height: 44px;" v-if="item.type===0">
                    <img src="../../../assets/weChat_group.png" style="width: 44px; height: 44px;" v-if="item.type===1">
                    <div style="width: 100%; height: 40px; display: flex; flex-direction: column; justify-content: space-between">
                        <div class="flex_between align_center" style="padding-left: 5px;">
                            <div class="name line-1 flex_1">{{item.type===0?item.friendWechatName:item.groupName}}</div>
                            <div class="time" style="padding-left: 20px;">{{formatTimeFun(item.lastSendTime)}}</div>
                        </div>

                        <div class="flex_between align_center" style="width: 100%;">
                            <div class="message line-1 flex_1" style="padding-left: 5px;">{{item.lastMessage}}</div>
                            <div class="state" :class="{active: item.automaticResponse}" @click.stop="handleStatus(item)">
                                <div class="dot dot_right" v-if="item.automaticResponse===1"></div>
                                <div class="dot dot_left" v-else></div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="flex align_center" style="padding: 0 40px;" v-if="isLoading">
                    <el-divider></el-divider>
                    <span class="el-icon-loading" style="padding: 0 15px; font-size: 20px"></span>
                    <el-divider></el-divider>
                </div>
            </template>
        </div>
        <autoReply :dialogTableVisible="dialogTableVisible" @beforeClose="dialogTableVisible=false" :categoryList="categoryList" ref="autoReplyChild" @callback="callback"></autoReply>
    </div>
</template>

<script>
import { mapState } from 'vuex';
import { toast, formatTime } from '@/common/tools'
import autoReply  from './autoReply.vue'
export default {
    components: {
        autoReply
    },
    data(){
        return {
            dialogTableVisible: false,
            automaticResponseNumber: {
                friend: 0,
                allFriend: 0,
                group: 0,
                allGroup: 0,
            },
            automaticResponses: [{name: "全部", type: ""}, {name: "已开启自动回复", type: 1}, {name: "未开启自动回复", type: 0}],
            automaticResponseType: "",
            automaticResponse: "全部",

            categoryList: [],
            category: "",
            categoryId: "",

            tags: ["高意向","中意向","低意向","了解产品详情", "询问价格", "询问使用方法", "询问发货时间", "询问售后服务", "非常满意", "满意", "一般", "不满意", "非常不满意", "产品质量", "发货时间", "售后服务", "使用问题", "价格问题", "新客户", "忠实客户", "活跃", "潜在", "流失"],
            tag: "",

            key: "",
            pageNum: 1,
            pageSize: 20,
            list: [],
            isLastPage: false,
            isEmpty: false,
            isLoading: false,

            current: 1,
        }
    },
    computed: {
        ...mapState({
            currentWeChat: state=> state.currentWeChat,
            weChatList: state=> state.weChatList,
            chatting: state=> state.chatting,
            currentChat: state=> state.currentChat,
            hasUnreadMsg: state=> state.hasUnreadMsg,
        })
    },

    created(){
        this.getCategoryList()
        if(this.$route.query.key && this.$route.query.current) {
            this.key = this.$route.query.key
            this.current = this.$route.query.current
        }
    },

    methods: {
        weChatChange(e){
            console.log(this.currentWeChat.currentWeChatId)
            console.log(e.wechatName, e.id)
            console.log(this.currentWeChat.currentWeChatId===e.id)
            // if(this.currentWeChat.currentWeChatId===e.id) return
            let obj = this.currentWeChat
            obj.currentWeChatId = e.id
            obj.currentUserWechatName = e.wechatName
            obj.currentOnLineStatus = e.status
            this.$store.state.currentWeChat = obj
            window.sessionStorage.setItem("currentWeChatId", e.id)
            window.sessionStorage.setItem("currentUserWechatName", e.wechatName)
            window.sessionStorage.setItem("currentOnLineStatus", e.status)
            this.$store.state.hasUnreadMsg = false
            this.$store.state.currentChat = {}
            this.$store.state.history = []
            setTimeout(() => {
                // this.list = []
                // this.pageNum = 1
                // this.getList()
                if(this.current===1) {
                    let obj = {
                        userWechatPrimaryId: this.currentWeChat.currentWeChatId,
                        userWechatName: this.currentWeChat.currentUserWechatName,
                        automaticResponse: this.automaticResponseType,
                        categoryId: this.categoryId || "",
                        tag: this.tag,
                        content: this.key,
                    }
                    this.$store.dispatch("getChatting", obj)
                }else{
                    this.reStart()
                }
            }, 200);
        },

        searchFun(){
            if(this.current===1) {
                let obj = {
                    userWechatPrimaryId: this.currentWeChat.currentWeChatId,
                    userWechatName: this.currentWeChat.currentUserWechatName,
                    automaticResponse: this.automaticResponseType,
                    categoryId: this.categoryId || "",
                    tag: this.tag,
                    content: this.key,
                }
                this.$store.dispatch("getChatting", obj)
            }else{
                this.reStart()
            }
        },

        automaticResponseChange(e){
            console.log(e)
            this.automaticResponse = e.name
            this.automaticResponseType = e.type
            // this.list = []
            // this.pageNum = 1
            // this.getList()
            if(this.current===1) {
                let obj = {
                    userWechatPrimaryId: this.currentWeChat.currentWeChatId,
                    userWechatName: this.currentWeChat.currentUserWechatName,
                    automaticResponse: this.automaticResponseType,
                    categoryId: this.categoryId || "",
                    tag: this.tag,
                    content: this.key,
                }
                this.$store.dispatch("getChatting", obj)
            }else{
                this.reStart()
            }
        },

        categoryChange(e){
            console.log(e)
            this.category = e.name
            this.categoryId = e.id
            // this.list = []
            // this.pageNum = 1
            // this.getList()
            if(this.current===1) {
                let obj = {
                    userWechatPrimaryId: this.currentWeChat.currentWeChatId,
                    userWechatName: this.currentWeChat.currentUserWechatName,
                    automaticResponse: this.automaticResponseType,
                    categoryId: this.categoryId || "",
                    tag: this.tag,
                    content: this.key,
                }
                this.$store.dispatch("getChatting", obj)
            }else{
                this.reStart()
            }
        },

        tagChange(e){
            console.log(e)
            this.tag = e
            // this.list = []
            // this.pageNum = 1
            // this.getList()
            if(this.current===1) {
                let obj = {
                    userWechatPrimaryId: this.currentWeChat.currentWeChatId,
                    userWechatName: this.currentWeChat.currentUserWechatName,
                    automaticResponse: this.automaticResponseType,
                    categoryId: this.categoryId || "",
                    tag: this.tag,
                    content: this.key,
                }
                this.$store.dispatch("getChatting", obj)
            }else{
                this.reStart()
            }
        },

        changeCurrent(index){
            if(this.current===index) return
            this.current = index
            if(this.current===1) {
                let obj = {
                    userWechatPrimaryId: this.currentWeChat.currentWeChatId,
                    userWechatName: this.currentWeChat.currentUserWechatName,
                    automaticResponse: this.automaticResponseType,
                    categoryId: this.categoryId || "",
                    tag: this.tag,
                    content: this.key,
                }
                this.$store.dispatch("getChatting", obj)
            }else {
                this.getFriendAndGroupAutomaticResponseNumber()
                this.reStart()
            }
        },

        toManage(){
            this.dialogTableVisible = true
            this.$refs.autoReplyChild.getList()
        },

        callback(){
            setTimeout(() => {
                this.getList()
                let obj = {
                    userWechatPrimaryId: this.currentWeChat.currentWeChatId,
                    userWechatName: this.currentWeChat.currentUserWechatName,
                    automaticResponse: this.automaticResponseType,
                    categoryId: this.categoryId || "",
                    tag: this.tag,
                    content: this.key,
                }
                this.$store.dispatch("getChatting", obj)
                console.log("callback")
            }, 1000);
        },

        // 去聊天
        toChat(item){
            this.$store.state.currentChat = item
            this.$emit("opration", 1)
            if(item.unreadNum && item.unreadNum>0) {
                this.$post("/front/wechat/friend/updateUnreadNum", {
                    id: item.id
                }).then(res=>{
                    if(res.data.code===0) {
                        this.$store.state.chatting.forEach(o=>{
                            if(o.id===item.id) o.unreadNum = 0
                            if(o.unreadNum && o.unreadNum>0) {
                                this.$store.state.hasUnreadMsg = true
                            }else {
                                this.$store.state.hasUnreadMsg = false
                            }
                        })
                    }
                })
            }
        },

        // 触底加载分页
        handleScroll(e){
            if(this.isLastPage || this.isLoading || this.current===1) return
            const { scrollTop, clientHeight, scrollHeight } = e.target
            if(scrollHeight - scrollTop - clientHeight < 10) {
                console.log("触底了")
                this.pageNum++
                this.isLoading = true
                this.getList()
            }
        },

        // 单个开启自动回复或关闭
        handleStatus(item){
            this.$post("/front/wechat/friend/modifyFriendAutomaticResponseType", {
                userWechatPrimaryId: this.currentWeChat.currentWeChatId,
                automaticResponse: item.automaticResponse===1 ? 0 : 1,
                friendWechatIdOrGroupWechatId: item.type===0 ? item.friendWechatId : item.groupId,
                type: item.type,
            }).then(res=>{
                if(res.data.code===0) {
                    toast(0, item.automaticResponse===0?"开启自动回复成功":"关闭自动回复成功")
                    if(this.current===1) {
                        this.$store.state.chatting.forEach(o=>{
                            if(o.id===item.id) o.automaticResponse = item.automaticResponse===1 ? 0 : 1 
                        }) 
                    }else {
                        this.list.forEach(o=>{
                            if(o.id===item.id) o.automaticResponse = item.automaticResponse===1 ? 0 : 1 
                        })
                    }
                }else{
                    toast(1, res.data.msg)
                }
            })
        },

        // 获取开启自动回复数量
        getFriendAndGroupAutomaticResponseNumber(){
            this.$post("/front/wechat/friend/friendAndGroupAutomaticResponseNumber", {
                userWechatPrimaryId: this.currentWeChat.currentWeChatId,
                userWechatName: this.currentWeChat.currentUserWechatName
            }).then(res=>{
                this.automaticResponseNumber = res.data.obj
            })
        },

        // 获取分组列表
        getCategoryList(){
            this.$post("/front/wechat/friend/categoryList").then(res=>{
                if(res.data.code===0) {
                    this.categoryList = res.data.obj
                }
            })
        },

        reStart(){
            this.pageNum = 1
            this.list = []
            this.getList()
        },

        // 获取列表
        getList(){
            this.$post("/front/wechat/friend/friendList", {
                pageNum: this.pageNum,
                pageSize: this.pageSize,
                userWechatPrimaryId: this.currentWeChat.currentWeChatId,
                automaticResponse: this.automaticResponseType,
                categoryId: this.categoryId || "",
                type: this.current===1 ?  0 : this.current-2,
                tag: this.tag,
                content: this.key,
                userWechatName: this.currentWeChat.currentUserWechatName
            }).then(res=>{
                if(res.data.code===0) {
                    
                    this.list = this.list.concat(res.data.obj.list)
                    this.isLastPage = res.data.obj.isLastPage
                    this.isEmpty = res.data.obj.list.length === 0
                    this.isLoading = false
                    console.log(this.list)
                }else{
                    this.isLoading = false
                    this.isLastPage = false
                }
            })
        },

        formatTimeFun(value){
            if(!value) return
            return formatTime(value*1000, "YMDHMS")
        },
    }
}
</script>

<style lang="less" scoped>
    .listVue {
        width: 350px;
        height: 100%;
        background: #fff;
        border-right: 1px solid #f5f5f5;
        padding: 15px 15px 0;
        .automaticResponseBtn {
            background: #DCDFE6;
            border-radius: 4px;
            width: 100%;
            height: 40px;
            line-height: 40px;
            text-align: center;
            color: #666;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            margin-top: 10px;
            span {
                font-size: 14px;
                font-weight: 500;
                color: #666;
            }
        }
        .tabVue {
            width: 100%;
            height: 40px;
            margin-top: 10px;
            .tab {
                width: 33.3333333%;
                height: 40px;
                line-height: 40px;
                text-align: center;
                background: #f5f5f5;
                cursor: pointer;
                font-size: 13px;
                position: relative;
            }
            .tab:nth-child(1) {
                border-radius: 5px 0 0 5px ;
            }
            .tab:nth-child(3) {
                border-radius: 0 5px 5px 0;
            }
            .active {
                background: #0147fd;
                color: #fff;
            }
            .textActive {
                color: #0147fd;
            }
            .chatTab {
                position: relative;
                
            }
            .chatTab::before {
                content: "";
                width: 10px;
                height: 10px;
                background: #d81e06;
                border-radius: 50%;
                position: absolute;
                top: -4px;
                right: -4px;
                z-index: 999;
            }
        } 

        .content {
            width: 100%;
            height: calc(100% - 250px);
            margin-top: 10px;
            overflow: scroll;
            .item {
                width: 100%;
                height: 60px;
                border-bottom: 1px solid #f5f5f5;
                cursor: pointer;
                padding: 0 8px;
                .name {
                    width: 100%;
                    color: #111;
                    font-weight: 600;
                    font-size: 13px;
                }
                .message, .time {
                    color: #AAA;
                    font-size: 13px;
                }
                .state {
                    width: 26px;
                    height: 15px;
                    background: #AAA;
                    border-radius: 10px;
                    position: relative;
                    margin-left: 20px;
                    cursor: pointer;
                    .dot {
                        width: 11px;
                        height: 11px;
                        background: #fff;
                        border-radius: 50%;
                        position: absolute;
                    }
                    .dot_left {
                        left: 2px;
                        top: 2px;
                    }
                    .dot_right {
                        right: 2px;
                        top: 2px;
                    }
                }
                .active {
                    background: #0147fd;
                }
            }
            .item:hover {
                background: #ececec;
            }
            .active {
                background: #ececec;
            }
        }
        .content::-webkit-scrollbar {
            width: 0;
            height: 0;
        }
    }
</style>